package com.yidu.ladder.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.yidu.ladder.system.domain.Log;
import com.yidu.ladder.system.service.LogService;

/**
 * 日志定时归档
 * @author bamboo
 *
 */
@Component
public class LogTimedTask {

	
	 @Autowired 
	 private LogService service;
	 

	@Scheduled(cron = "0 15 10 ? * *")
	public void archives() throws IOException {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//定义一个路径
		String filePath = "D:\\LOG\\log.txt";
		//创建文件
		File file = new File(filePath);
		//判断文件是否存在
		if (file.exists()) {
			System.out.println("文件已经存在");
		} else {//如果不存在
			//创建一个文件
			file.createNewFile();
			//定义一个字符缓存输出流 
			BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath));
			//将归档的时间存入map集合中
			Map<String, Date> statisticsTime = getStatisticsTime();
			//调用service方法 将开始时间和结束时间传入
			List<Log> logs = service.selectLogByLogTime(statisticsTime.get("startTime"),
					statisticsTime.get("stopTime"));
			//定义个字符串
			String content = "物流日志";
			//将字符串输出到文件
			bufferedWriter.write(content);
			//变量查询的数据
			for (Log log : logs) {
				//将时间格式化为字符串
				String logTime = df.format(log.getOperateTime());
				//将遍历的数据存到content变量中
				content = "\r\n" + "日志id:"+ log.getLogId()+ "  "  + "用户名:" + log.getUserName()+ "  "  + "操作类型:" + log.getOperateType()+ "  "  + "操作事件:" + log.getOperateEvent()+ "  " 
						+ "操作时间:" + logTime+ "  "  + "ip地址:" + log.getHost();
				//将content写入文件
				bufferedWriter.write(content);
			}
			//调用删除烦方法
			service.deleteLogByLogTime(statisticsTime.get("startTime"), statisticsTime.get("stopTime"));
			//关闭输出流
			bufferedWriter.close();
		}

	}

	/**
	 * 获取需要归档的时间
	 * 
	 * @return 返回时间map
	 */
	private Map<String, Date> getStatisticsTime() {
		//创建对象
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.MILLISECOND, 0);
		calendar.set(Calendar.SECOND, 59);
		calendar.set(Calendar.MINUTE, 59);
		calendar.set(Calendar.HOUR_OF_DAY, 23);
		calendar.add(Calendar.DATE, -1);
		//结束时间
		Date stopTime = calendar.getTime();
		Calendar calendar1 = Calendar.getInstance();
		//开始时间
		calendar1.add(Calendar.DATE, -29);
		Date startTime = calendar1.getTime();
		HashMap<String, Date> timeMap = new HashMap<>();
		timeMap.put("stopTime", stopTime);
		timeMap.put("startTime", startTime);
		return timeMap;
	}
}
